<template>
  <div class="parking-page">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
      >
        <Breadcrumb
          :items="[{ path: '/', title: '首页' }, { title: '停车场' }]"
        />
      </div>

      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              停车服务
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              查看停车场实时信息，预约停车位
            </p>
          </div>
          <el-button class="back-btn" @click="router.back()">
            <el-icon class="mr-1"><Back /></el-icon>
            返回上一页
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧停车场列表 -->
        <div class="lg:col-span-2">
          <!-- 搜索和筛选 -->
          <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-6">
            <el-input
              v-model="searchQuery"
              placeholder="搜索停车场"
              class="w-full mb-4"
              clearable
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <div class="flex items-center justify-start">
              <el-radio-group v-model="parkingFilter" size="large">
                <el-radio-button label="all">全部</el-radio-button>
                <el-radio-button label="available">有空位</el-radio-button>
                <el-radio-button label="full">已满</el-radio-button>
              </el-radio-group>
            </div>
          </div>

          <!-- 停车场列表 -->
          <div class="space-y-4">
            <div
              v-for="parking in filteredParkings"
              :key="parking.id"
              class="parking-card bg-white dark:bg-gray-800 rounded-lg shadow-md overflow-hidden hover:shadow-lg transition-shadow"
              @click="selectParking(parking)"
            >
              <div class="flex p-4">
                <div
                  class="parking-icon w-16 h-16 rounded-lg bg-primary-100 flex items-center justify-center flex-shrink-0"
                >
                  <el-icon class="text-3xl text-primary-600"><Van /></el-icon>
                </div>
                <div class="ml-4 flex-1">
                  <div class="flex items-start justify-between">
                    <div>
                      <h3 class="text-lg font-medium mb-1">
                        {{ parking.name }}
                      </h3>
                      <p class="text-gray-600 text-sm mb-2">
                        {{ parking.address }}
                      </p>
                    </div>
                    <el-tag
                      :type="
                        parking.status === 'available' ? 'success' : 'danger'
                      "
                    >
                      {{ parking.status === "available" ? "有空位" : "已满" }}
                    </el-tag>
                  </div>
                  <div class="grid grid-cols-3 gap-4 mt-2">
                    <div class="text-center p-2 stat-box rounded">
                      <div class="text-lg font-medium text-primary-600">
                        {{ parking.totalSpots }}
                      </div>
                      <div class="text-sm text-gray-500">总车位</div>
                    </div>
                    <div class="text-center p-2 stat-box rounded">
                      <div class="text-lg font-medium text-green-600">
                        {{ parking.availableSpots }}
                      </div>
                      <div class="text-sm text-gray-500">空余车位</div>
                    </div>
                    <div class="text-center p-2 stat-box rounded">
                      <div class="text-lg font-medium text-blue-600">
                        {{ parking.price }}元/小时
                      </div>
                      <div class="text-sm text-gray-500">收费标准</div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="border-t px-4 py-3 bg-gray-50 dark:bg-gray-700/50">
                <div class="flex items-center justify-between text-sm">
                  <div class="flex items-center space-x-4">
                    <span
                      class="flex items-center text-gray-600 dark:text-gray-300"
                    >
                      <el-icon class="mr-1"><Timer /></el-icon>
                      24小时开放
                    </span>
                    <span
                      class="flex items-center text-gray-600 dark:text-gray-300"
                    >
                      <el-icon class="mr-1"><Location /></el-icon>
                      距景区{{ parking.distance }}
                    </span>
                  </div>
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="handleNavigation(parking)"
                  >
                    <el-icon class="mr-1"><Guide /></el-icon>
                    导航前往
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧地图 -->
        <div class="lg:col-span-1">
          <div class="sticky top-24 space-y-6">
            <!-- 停车场统计 -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
              <h3
                class="text-lg font-medium text-gray-900 dark:text-white mb-4"
              >
                停车场统计
              </h3>
              <div class="grid grid-cols-2 gap-4">
                <div
                  class="bg-primary-50 dark:bg-primary-900/20 rounded-lg p-4"
                >
                  <div
                    class="text-2xl font-bold text-primary-600 dark:text-primary-400"
                  >
                    {{ totalParkingSpots }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    总车位
                  </div>
                </div>
                <div class="bg-green-50 dark:bg-green-900/20 rounded-lg p-4">
                  <div
                    class="text-2xl font-bold text-green-600 dark:text-green-400"
                  >
                    {{ totalAvailableSpots }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    空余车位
                  </div>
                </div>
                <div class="bg-blue-50 dark:bg-blue-900/20 rounded-lg p-4">
                  <div
                    class="text-2xl font-bold text-blue-600 dark:text-blue-400"
                  >
                    {{ parkings.length }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    停车场数量
                  </div>
                </div>
                <div class="bg-yellow-50 dark:bg-yellow-900/20 rounded-lg p-4">
                  <div
                    class="text-2xl font-bold text-yellow-600 dark:text-yellow-400"
                  >
                    {{ averagePrice }}
                  </div>
                  <div class="text-sm text-gray-600 dark:text-gray-400">
                    平均价格
                  </div>
                </div>
              </div>
            </div>

            <!-- 地图 -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-4">
              <div class="map-container">
                <div v-if="!mapLoaded" class="flex items-center justify-center h-full">
                  <el-icon class="text-4xl text-primary-500 animate-spin"><Loading /></el-icon>
                  <p class="ml-3 text-gray-600">正在加载地图...</p>
                </div>
                <div ref="mapContainer" style="width:100%;height:400px;"></div>
              </div>
            </div>

            <!-- 停车提示 -->
            <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
              <h3
                class="text-lg font-medium text-gray-900 dark:text-white mb-4"
              >
                停车提示
              </h3>
              <div class="space-y-4">
                <div class="flex items-start space-x-3">
                  <el-icon class="text-primary-500 text-xl mt-0.5"
                    ><InfoFilled
                  /></el-icon>
                  <p class="text-gray-600 dark:text-gray-400">
                    请注意遵守停车场的管理规定，按照标识指引有序停放。
                  </p>
                </div>
                <div class="flex items-start space-x-3">
                  <el-icon class="text-yellow-500 text-xl mt-0.5"
                    ><Warning
                  /></el-icon>
                  <p class="text-gray-600 dark:text-gray-400">
                    高峰时段建议提前规划路线，选择合适的停车场。
                  </p>
                </div>
                <div class="flex items-start space-x-3">
                  <el-icon class="text-green-500 text-xl mt-0.5"
                    ><Promotion
                  /></el-icon>
                  <p class="text-gray-600 dark:text-gray-400">
                    部分停车场支持微信、支付宝等移动支付方式。
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  Search,
  Van,
  Timer,
  Location,
  Guide,
  InfoFilled,
  Warning,
  Promotion,
  Back,
  Loading,
} from "@element-plus/icons-vue";
import Breadcrumb from "@/components/global/Breadcrumb.vue";

const router = useRouter();

// 高德地图相关 - 在脚本执行初期就设置安全配置
const mapKey = "ac63e78c8bfb172aac3c5be005a25f28"; // 高德地图Key
const securityJsCode = "bddeaa4d8587f8b446342a53ee0d4994"; // 高德地图安全密钥
const mapContainer = ref(null);
let map = null;
let markers = [];
const mapLoaded = ref(false);

// 设置高德地图安全密钥配置 - 在任何脚本执行前设置
if (typeof window !== 'undefined') {
  window._AMapSecurityConfig = {
    securityJsCode: securityJsCode
  };
}

// 停车场筛选
const parkingFilter = ref("all");
const searchQuery = ref("");

// 真实的贵港市停车场数据
const parkings = ref([
  {
    id: 1,
    name: "贵港文化中心地下停车场",
    address: "广西壮族自治区贵港市港北区民主路369号贵港文化中心",
    status: "available",
    totalSpots: 200,
    availableSpots: 45,
    price: 5,
    distance: "50米",
    location: [110.074906, 23.107123], 
  },
  {
    id: 2,
    name: "贵港江滨公园停车场",
    address: "广西壮族自治区贵港市港北区江滨公园北门",
    status: "available",
    totalSpots: 150,
    availableSpots: 20,
    price: 4,
    distance: "100米",
    location: [110.082545, 23.111235],
  },
  {
    id: 3,
    name: "贵港商业中心停车场",
    address: "广西壮族自治区贵港市港北区金港大道399号附近",
    status: "full",
    totalSpots: 300,
    availableSpots: 0,
    price: 6,
    distance: "200米",
    location: [110.078856, 23.109345],
  },
  {
    id: 4,
    name: "贵港市体育中心停车场",
    address: "广西壮族自治区贵港市港北区金港大道与民主路交叉口",
    status: "available",
    totalSpots: 250,
    availableSpots: 120,
    price: 5,
    distance: "500米",
    location: [110.071645, 23.105678],
  },
  {
    id: 5,
    name: "贵港市政府停车场",
    address: "广西壮族自治区贵港市港北区金港大道255号",
    status: "available",
    totalSpots: 180,
    availableSpots: 35,
    price: 6,
    distance: "800米",
    location: [110.079432, 23.103456],
  }
]);

// 过滤停车场
const filteredParkings = computed(() => {
  let result = parkings.value;

  // 按状态筛选
  if (parkingFilter.value !== "all") {
    result = result.filter((parking) => parking.status === parkingFilter.value);
  }

  // 按关键词搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    result = result.filter(
      (parking) =>
        parking.name.toLowerCase().includes(query) ||
        parking.address.toLowerCase().includes(query),
    );
  }

  return result;
});

// 选中的停车场
const selectedParking = ref(null);

// 加载高德地图脚本 - 完全重写
const loadAMapScript = () => {
  return new Promise((resolve, reject) => {
    // 清除之前可能存在的脚本，防止冲突
    const existingScript = document.querySelector('script[src*="webapi.amap.com"]');
    if (existingScript) {
      existingScript.parentNode.removeChild(existingScript);
    }
    
    // 重置 AMap 对象，防止使用旧的实例
    if (window.AMap) {
      window.AMap = undefined;
    }
    
    // 确保安全配置已设置
    if (typeof window !== 'undefined' && !window._AMapSecurityConfig) {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
    }
    
    // 添加时间戳防止缓存
    const timestamp = new Date().getTime();
    
    // 创建并加载脚本
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.async = true;
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${mapKey}&plugin=AMap.Scale,AMap.ToolBar,AMap.Geocoder,AMap.Driving&t=${timestamp}`;
    
    script.onload = () => {
      console.log('高德地图脚本加载成功，使用密钥:', mapKey);
      mapLoaded.value = true;
      resolve(window.AMap);
    };
    
    script.onerror = (error) => {
      console.error('高德地图脚本加载失败:', error);
      mapLoaded.value = false;
      reject(new Error('高德地图API加载失败，请检查网络连接或API密钥'));
    };
    
    document.head.appendChild(script);
  });
};

// 添加停车场标记
const addParkingMarkers = () => {
  // 清除之前的标记
  if (markers.length > 0) {
    markers.forEach(item => {
      if (item.marker) {
        item.marker.remove();
      }
    });
    markers = [];
  }

  // 添加新标记
  parkings.value.forEach((p) => {
    try {
      // 使用简单的Marker，不使用自定义HTML
      const marker = new AMap.Marker({
        position: p.location,
        map: map,
        title: p.name,
        icon: new AMap.Icon({
          size: new AMap.Size(40, 40),
          image: p.status === 'available' ? 
            'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png' : 
            'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
          imageSize: new AMap.Size(40, 40)
        }),
        offset: new AMap.Pixel(-20, -40)
      });

      // 添加信息窗体
      const infoWindow = new AMap.InfoWindow({
        content: `
          <div style="padding:10px;">
            <h3 style="font-weight:bold;margin-bottom:5px;">${p.name}</h3>
            <p style="font-size:12px;color:#666;margin-bottom:5px;">${p.address}</p>
            <p style="font-size:12px;margin-top:5px;">
              <span style="color:#1890ff;">空位：${p.availableSpots}</span> / 
              <span>总位：${p.totalSpots}</span>
            </p>
            <p style="font-size:12px;margin-top:5px;">收费标准：${p.price}元/小时</p>
          </div>
        `,
        offset: new AMap.Pixel(0, -30)
      });

      // 点击标记时显示信息窗体
      marker.on("click", () => {
        infoWindow.open(map, marker.getPosition());
        selectParking(p);
      });

      // 保存标记引用
      markers.push({
        id: p.id,
        marker: marker,
        infoWindow: infoWindow
      });
    } catch (e) {
      console.warn("添加标记失败:", e);
    }
  });
};

// 高亮显示指定的标记 - 修复动画问题
const highlightMarker = (parkingId) => {
  try {
    markers.forEach(item => {
      if (item.id === parkingId) {
        // 放大图标显示选中状态
        item.marker.setTop(true);  // 置于其他标记之上
        
        // 打开信息窗口
        item.infoWindow.open(map, item.marker.getPosition());
      } else {
        // 恢复其他标记
        item.marker.setTop(false);
        item.infoWindow.close();
      }
    });
  } catch (e) {
    console.warn("高亮标记失败:", e);
  }
};

// 初始化地图
const initMap = async (parking) => {
  try {
    console.log("开始初始化地图...");

    // 确保地图容器存在
    if (!mapContainer.value) {
      throw new Error("地图容器不存在");
    }

    // 加载高德地图脚本
    await loadAMapScript();

    // 如果地图已存在，只更新位置和视图
    if (map) {
      console.log("地图已存在，更新位置");
      
      if (parking) {
        // 如果选中了停车场，则聚焦到该停车场
        map.setCenter(parking.location);
        map.setZoom(16);
        highlightMarker(parking.id);
      } else {
        // 否则展示贵港市全貌
        map.setCenter([110.079167, 23.11365]); // 贵港市中心坐标
        map.setZoom(13); // 设置合适的缩放级别以查看整个城市
      }
      
      return;
    }

    console.log("创建新地图实例");

    // 确保容器有明确的尺寸
    if (mapContainer.value) {
      mapContainer.value.style.width = '100%';
      mapContainer.value.style.height = '400px';
    }

    // 贵港市中心坐标
    const guigangCenter = [110.079167, 23.11365];
    // 创建地图实例，默认显示贵港市全貌
    const center = parking ? parking.location : guigangCenter;
    const zoom = parking ? 16 : 13; // 如果选择了停车场则放大显示，否则显示整个贵港市

    // 使用最简单的配置创建地图
    map = new AMap.Map(mapContainer.value, {
      zoom: zoom,
      center: center,
      resizeEnable: true
    });

    // 添加基本控件
    map.addControl(new AMap.Scale());
    map.addControl(new AMap.ToolBar({
      position: 'RB'
    }));

    // 确保地图加载完成后再添加标记
    map.on('complete', () => {
      try {
        // 添加所有停车场标记
        addParkingMarkers();
        
        // 如果有选中的停车场，高亮显示
        if (parking) {
          highlightMarker(parking.id);
        }
        
        console.log("地图标记添加成功");
      } catch (e) {
        console.warn("添加地图标记失败:", e);
      }
    });

    console.log("地图初始化成功");
  } catch (error) {
    console.error("地图初始化失败:", error);
    ElMessage.error(`地图加载失败: ${error.message}`);
  }
};

// 选择停车场
const selectParking = (parking) => {
  selectedParking.value = parking;
  
  // 确保在 nextTick 后初始化地图
  nextTick(() => {
    initMap(parking);
  });
};

// 导航功能
const handleNavigation = async (parking) => {
  try {
    if (!mapLoaded.value) {
      await loadAMapScript();
    }
    
    // 弹出输入框让用户输入起点
    const { value: startAddress } = await ElMessageBox.prompt(
      "请输入起点地址",
      "导航",
      {
        confirmButtonText: "开始导航",
        cancelButtonText: "取消",
        inputPlaceholder: "例如：贵港市政府",
      },
    );

    if (startAddress) {
      // 使用地理编码服务将地址转换为坐标
      const geocoder = new AMap.Geocoder();

      geocoder.getLocation(startAddress, (status, result) => {
        if (status === "complete" && result.geocodes.length) {
          const startLocation = result.geocodes[0].location;

          // 打开高德地图导航
          const url = `https://uri.amap.com/navigation?from=${startLocation.lng},${startLocation.lat},${startAddress}&to=${parking.location[0]},${parking.location[1]},${parking.name}&mode=car&policy=1`;
          window.open(url, "_blank");

          ElMessage.success("正在为您规划路线...");
        } else {
          ElMessage.error("找不到该地址，请输入更详细的地址");
        }
      });
    }
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("导航失败，请重试");
    }
  }
};

// 计算停车场统计数据
const totalParkingSpots = computed(() => {
  return parkings.value.reduce((sum, parking) => sum + parking.totalSpots, 0);
});

const totalAvailableSpots = computed(() => {
  return parkings.value.reduce(
    (sum, parking) => sum + parking.availableSpots,
    0,
  );
});

const averagePrice = computed(() => {
  const total = parkings.value.reduce((sum, parking) => sum + parking.price, 0);
  return Math.round(total / parkings.value.length);
});

// 在组件挂载时初始化地图
onMounted(async () => {
  try {
    console.log("组件挂载，准备初始化地图");
    
    // 确保在任何地图操作前设置安全配置
    if (typeof window !== 'undefined') {
      window._AMapSecurityConfig = {
        securityJsCode: securityJsCode
      };
      console.log("已设置高德地图安全配置");
    }
    
    // 确保DOM已更新
    await nextTick();
    
    // 确保容器已渲染 - 延迟一下初始化
    setTimeout(() => {
      initMap();
    }, 300);
  } catch (error) {
    console.error("组件挂载时初始化地图失败:", error);
  }
});

// 在组件卸载时清理地图实例
onUnmounted(() => {
  if (map) {
    map.destroy();
    map = null;
  }
});
</script>

<style lang="scss" scoped>
.parking-page {
  @apply min-h-screen bg-gray-50 dark:bg-gray-900;

  .page-header {
    @apply mb-6;

    h1 {
      @apply text-gray-900 dark:text-white;
    }

    p {
      @apply text-gray-600 dark:text-gray-400;
    }
  }

  .parking-card {
    @apply cursor-pointer bg-white dark:bg-gray-800;

    &:hover {
      .parking-icon {
        @apply bg-primary-200 dark:bg-primary-900/40;
      }
    }

    .parking-icon {
      @apply bg-primary-100 dark:bg-primary-900/20;

      .el-icon {
        @apply text-primary-600 dark:text-primary-400;
      }
    }

    p {
      @apply text-gray-600 dark:text-gray-400;
    }

    .stat-box {
      @apply bg-gray-50 dark:bg-gray-700;
    }
  }

  :deep(.el-radio-button__inner) {
    @apply dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600;

    &:hover {
      @apply dark:bg-gray-600;
    }
  }

  :deep(.el-radio-button__original-radio:checked + .el-radio-button__inner) {
    @apply dark:bg-primary-600 dark:text-white dark:border-primary-600;
  }

  :deep(.el-input__wrapper) {
    @apply dark:bg-gray-700 dark:border-gray-600;

    input {
      @apply dark:text-gray-300;

      &::placeholder {
        @apply dark:text-gray-500;
      }
    }
  }

  :deep(.el-tag) {
    &.el-tag--success {
      @apply dark:bg-green-900/60 dark:text-green-300 dark:border-green-700;
    }
    &.el-tag--danger {
      @apply dark:bg-red-900/60 dark:text-red-300 dark:border-red-700;
    }
  }

  :deep(.el-button) {
    &.el-button--primary {
      @apply dark:bg-primary-600 dark:border-primary-600 dark:text-white;

      &:hover {
        @apply dark:bg-primary-500 dark:border-primary-500;
      }
    }
  }

  // 地图容器样式
  .map-container {
    @apply relative bg-gray-100 dark:bg-gray-700 rounded-lg;
    height: 400px;
    width: 100%;
  }
}
</style>
